"""
MCP服务管理器
处理MCP服务器的调用、管理和监控
"""

from typing import Dict, Any, Optional
from typing import Dict, Any, Optional, List
import requests
import json
import asyncio
import aiohttp
from requests.adapters import HTTPAdapter
from src.config.settings import settings
from src.utils.logging import get_logger
from src.services.monitoring_service import monitoring_service
from src.utils.mcp_compatibility_checker import MCPPluginCompatibilityChecker
import traceback
import time

logger = get_logger(__name__)


class MCPServiceError(Exception):
    """MCP服务异常基类"""
    def __init__(self, message: str, error_code: str = "MCP_SERVICE_ERROR", details: Optional[Dict[str, Any]] = None):
        self.message = message
        self.error_code = error_code
        self.details = details or {}
        super().__init__(self.message)


class MCPConnectionError(MCPServiceError):
    """MCP连接异常"""
    def __init__(self, message: str, details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "MCP_CONNECTION_ERROR", details)


class MCPAuthenticationError(MCPServiceError):
    """MCP认证异常"""
    def __init__(self, message: str, details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "MCP_AUTHENTICATION_ERROR", details)


class MCPTimeoutError(MCPServiceError):
    """MCP超时异常"""
    def __init__(self, message: str, details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "MCP_TIMEOUT_ERROR", details)


class MCPToolError(MCPServiceError):
    """MCP工具执行异常"""
    def __init__(self, message: str, details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "MCP_TOOL_ERROR", details)


class MCPServiceManager:
    """MCP服务管理器"""
    
    def __init__(self):
        self.session = requests.Session()
        # 设置适配器以处理连接池和重试
        self.session.mount('http://', HTTPAdapter(max_retries=3))
        self.session.mount('https://', HTTPAdapter(max_retries=3))
        self._setup_monitoring()
        self.compatibility_checker = MCPPluginCompatibilityChecker()
        # 添加缓存机制
        self._status_cache = {}
        self._status_cache_ttl = 30  # 30秒缓存
        self._tool_result_cache = {}
        self._tool_result_cache_ttl = 60  # 60秒缓存
        # 添加反馈处理机制
        self._feedback_history = {}  # 存储用户反馈历史
        self._feedback_cache = {}    # 缓存反馈处理结果
    
    def _setup_monitoring(self):
        """设置监控"""
        try:
            # 初始化MCP服务器连接指标
            for server_name in settings.MCP_SERVERS:
                monitoring_service.record_mcp_server_connection(server_name, 0)
        except Exception as e:
            logger.warning(f"初始化MCP监控失败: {e}")
    
    def is_server_available(self, server_name: str) -> bool:
        """
        检查MCP服务器是否可用
        
        Args:
            server_name: 服务器名称
            
        Returns:
            服务器是否可用
        """
        if not settings.MCP_ENABLED:
            return False
            
        return settings.is_mcp_server_enabled(server_name)
    
    def get_server_config(self, server_name: str) -> dict[str, Any]:
        """
        获取服务器配置
        
        Args:
            server_name: 服务器名称
            
        Returns:
            服务器配置
        """
        return settings.get_mcp_server_config(server_name)
    
    def _log_error_with_context(self, error: Exception, context: Dict[str, Any]):
        """
        记录带上下文信息的错误日志
        
        Args:
            error: 异常对象
            context: 上下文信息
        """
        error_details = {
            "error_type": type(error).__name__,
            "error_message": str(error),
            "timestamp": time.time(),
            "context": context,
            "traceback": traceback.format_exc()
        }
        
        logger.error(f"MCP服务错误: {error_details}")
    
    def _handle_retry_logic(self, attempt: int, retries: int, error: Exception, 
                           server_name: str, tool_name: str, operation: str) -> bool:
        """
        处理重试逻辑
        
        Args:
            attempt: 当前尝试次数
            retries: 最大重试次数
            error: 发生的错误
            server_name: 服务器名称
            tool_name: 工具名称
            operation: 操作名称
            
        Returns:
            是否应该继续重试
        """
        import random
        
        # 记录错误到历史
        error_info = {
            "attempt": attempt + 1,
            "error_type": type(error).__name__,
            "error_message": str(error),
            "timestamp": time.time()
        }
        
        logger.warning(f"MCP工具{operation}失败 (尝试 {attempt + 1}/{retries}): {error}")
        
        # 对于某些特定错误，可以提前终止重试
        if isinstance(error, MCPAuthenticationError):
            logger.error(f"MCP认证失败，终止重试: {server_name}:{tool_name}")
            return False
            
        # 指数退避延迟
        if attempt < retries - 1:
            delay = (2 ** attempt) + (random.uniform(0, 1))
            logger.info(f"等待 {delay:.2f} 秒后进行下次重试")
            time.sleep(delay)
            
        return True
    
    def _create_error_recovery_context(self, server_name: str, tool_name: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
        """
        创建错误恢复上下文
        
        Args:
            server_name: 服务器名称
            tool_name: 工具名称
            parameters: 参数
            
        Returns:
            错误恢复上下文
        """
        return {
            "server_name": server_name,
            "tool_name": tool_name,
            "parameters": parameters,
            "server_config": self.get_server_config(server_name),
            "attempt_count": 0,
            "max_retries": 3,
            "last_error": None
        }
    
    def call_tool_sync(self, server_name: str, tool_name: str, parameters: Dict[str, Any], 
                       caller: str = "unknown", workflow: str = "unknown") -> Dict[str, Any]:
        """
        同步调用MCP工具
        
        Args:
            server_name: 服务器名称
            tool_name: 工具名称
            parameters: 参数字典
            caller: 调用者信息
            workflow: 工作流信息
            
        Returns:
            工具调用结果
            
        Raises:
            MCPServiceError: 调用失败时抛出
        """
        if not self.is_server_available(server_name):
            error_details = {
                "server_name": server_name,
                "reason": "服务器不可用或未启用"
            }
            self._log_error_with_context(
                MCPServiceError(f"MCP服务器 {server_name} 不可用", "SERVER_UNAVAILABLE", error_details),
                {"operation": "server_availability_check", "server_name": server_name}
            )
            # 记录插件错误统计
            monitoring_service.record_mcp_plugin_error("unknown", server_name, tool_name, "SERVER_UNAVAILABLE")
            raise MCPServiceError(f"MCP服务器 {server_name} 不可用", "SERVER_UNAVAILABLE", error_details)
        
        start_time = time.time()
        status = "success"
        error_context = {
            "operation": "call_tool_sync",
            "server_name": server_name,
            "tool_name": tool_name,
            "parameters": parameters,
            "caller": caller,
            "workflow": workflow
        }
        
        try:
            config = self.get_server_config(server_name)
            url = config.get('url', '')
            
            if not url:
                error_details = {
                    "server_name": server_name,
                    "reason": "未配置URL"
                }
                # 记录插件错误统计
                monitoring_service.record_mcp_plugin_error("unknown", server_name, tool_name, "MISSING_URL_CONFIG")
                raise MCPServiceError(f"MCP服务器 {server_name} 未配置URL", "MISSING_URL_CONFIG", error_details)
            
            # 构造请求
            headers = {
                'Content-Type': 'application/json',
            }
            
            api_key = config.get('api_key', '')
            if api_key:
                headers['Authorization'] = f"Bearer {api_key}"
            
            payload = {
                "tool": tool_name,
                "parameters": parameters
            }
            
            timeout = config.get('timeout', 30)
            retries = config.get('retries', 3)
            
            # 发送请求（带重试机制）
            for attempt in range(retries):
                try:
                    # 标准化URL路径
                    from urllib.parse import urljoin, urlparse
                    normalized_url = urljoin(url.rstrip('/') + '/', tool_name.lstrip('/'))
                    
                    response = self.session.post(
                        normalized_url,
                        headers=headers,
                        json=payload,
                        timeout=timeout
                    )
                    
                    # 检查响应状态码
                    if response.status_code == 401:
                        raise MCPAuthenticationError(f"认证失败: {response.status_code}", {
                            "server_name": server_name,
                            "status_code": response.status_code,
                            "response_text": response.text[:200]  # 限制日志长度
                        })
                    elif response.status_code == 404:
                        raise MCPToolError(f"工具未找到: {tool_name}", {
                            "server_name": server_name,
                            "tool_name": tool_name,
                            "status_code": response.status_code
                        })
                    elif response.status_code >= 500:
                        raise MCPServiceError(f"服务器内部错误: {response.status_code}", "SERVER_ERROR", {
                            "server_name": server_name,
                            "status_code": response.status_code,
                            "response_text": response.text[:200]
                        })
                    elif response.status_code >= 400:
                        raise MCPServiceError(f"客户端错误: {response.status_code}", "CLIENT_ERROR", {
                            "server_name": server_name,
                            "status_code": response.status_code,
                            "response_text": response.text[:200]
                        })
                    
                    response.raise_for_status()
                    result = response.json()
                    return result
                except requests.Timeout as e:
                    if attempt == retries - 1:  # 最后一次尝试
                        # 记录插件错误统计
                        monitoring_service.record_mcp_plugin_error("unknown", server_name, tool_name, "TIMEOUT")
                        raise MCPTimeoutError(f"调用MCP工具超时: {str(e)}", {
                            "server_name": server_name,
                            "tool_name": tool_name,
                            "timeout": timeout,
                            "attempt": attempt + 1
                        }) from e
                    # 使用新的重试逻辑处理
                    if not self._handle_retry_logic(attempt, retries, e, server_name, tool_name, "同步调用"):
                        raise
                except requests.ConnectionError as e:
                    if attempt == retries - 1:  # 最后一次尝试
                        # 记录插件错误统计
                        monitoring_service.record_mcp_plugin_error("unknown", server_name, tool_name, "CONNECTION_ERROR")
                        raise MCPConnectionError(f"连接MCP服务器失败: {str(e)}", {
                            "server_name": server_name,
                            "tool_name": tool_name,
                            "attempt": attempt + 1
                        }) from e
                    # 使用新的重试逻辑处理
                    if not self._handle_retry_logic(attempt, retries, e, server_name, tool_name, "同步连接"):
                        raise
                except requests.RequestException as e:
                    if attempt == retries - 1:  # 最后一次尝试
                        # 记录插件错误统计
                        monitoring_service.record_mcp_plugin_error("unknown", server_name, tool_name, "REQUEST_ERROR")
                        raise MCPServiceError(f"调用MCP工具失败: {str(e)}", "REQUEST_ERROR", {
                            "server_name": server_name,
                            "tool_name": tool_name,
                            "attempt": attempt + 1
                        }) from e
                    # 使用新的重试逻辑处理
                    if not self._handle_retry_logic(attempt, retries, e, server_name, tool_name, "同步请求"):
                        raise
            
            # 添加默认返回值以避免返回None
            return {"status": "unknown", "message": "未知错误"}
        except MCPServiceError:
            # 重新抛出已知的MCP异常
            status = "error"
            raise
        except Exception as e:
            status = "error"
            error_details = {
                "server_name": server_name,
                "tool_name": tool_name,
                "error_type": type(e).__name__,
                "error_message": str(e)
            }
            self._log_error_with_context(e, error_context)
            # 记录插件错误统计
            monitoring_service.record_mcp_plugin_error("unknown", server_name, tool_name, "UNEXPECTED_ERROR")
            raise MCPServiceError(f"MCP工具调用失败: {str(e)}", "UNEXPECTED_ERROR", error_details) from e
        finally:
            # 记录监控指标
            try:
                duration = time.time() - start_time
                monitoring_service.record_mcp_server_request(server_name, tool_name, status, duration)
                # 记录调用链追踪
                monitoring_service.record_mcp_call_trace(server_name, tool_name, status, caller, workflow)
                monitoring_service.record_mcp_call_latency(server_name, tool_name, duration, caller, workflow)
                # 记录插件响应时间
                monitoring_service.record_mcp_plugin_response_time("unknown", server_name, tool_name, duration)
            except Exception as e:
                logger.warning(f"记录MCP监控指标失败: {e}")
    
    async def call_tool_async(self, server_name: str, tool_name: str, parameters: Dict[str, Any],
                              caller: str = "unknown", workflow: str = "unknown") -> Dict[str, Any]:
        """
        异步调用MCP工具
        
        Args:
            server_name: 服务器名称
            tool_name: 工具名称
            parameters: 参数字典
            caller: 调用者信息
            workflow: 工作流信息
            
        Returns:
            工具调用结果
            
        Raises:
            MCPServiceError: 调用失败时抛出
        """
        if not self.is_server_available(server_name):
            error_details = {
                "server_name": server_name,
                "reason": "服务器不可用或未启用"
            }
            self._log_error_with_context(
                MCPServiceError(f"MCP服务器 {server_name} 不可用", "SERVER_UNAVAILABLE", error_details),
                {"operation": "server_availability_check", "server_name": server_name}
            )
            # 记录插件错误统计
            monitoring_service.record_mcp_plugin_error("unknown", server_name, tool_name, "SERVER_UNAVAILABLE")
            raise MCPServiceError(f"MCP服务器 {server_name} 不可用", "SERVER_UNAVAILABLE", error_details)
        
        start_time = asyncio.get_event_loop().time()
        status = "success"
        error_context = {
            "operation": "call_tool_async",
            "server_name": server_name,
            "tool_name": tool_name,
            "parameters": parameters,
            "caller": caller,
            "workflow": workflow
        }
        
        try:
            config = self.get_server_config(server_name)
            url = config.get('url', '')
            
            if not url:
                error_details = {
                    "server_name": server_name,
                    "reason": "未配置URL"
                }
                # 记录插件错误统计
                monitoring_service.record_mcp_plugin_error("unknown", server_name, tool_name, "MISSING_URL_CONFIG")
                raise MCPServiceError(f"MCP服务器 {server_name} 未配置URL", "MISSING_URL_CONFIG", error_details)
            
            # 构造请求
            headers = {
                'Content-Type': 'application/json',
            }
            
            api_key = config.get('api_key', '')
            if api_key:
                headers['Authorization'] = f"Bearer {api_key}"
            
            payload = {
                "tool": tool_name,
                "parameters": parameters
            }
            
            timeout = config.get('timeout', 30)
            retries = config.get('retries', 3)
            
            # 发送请求（带重试机制）
            for attempt in range(retries):
                try:
                    async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=timeout)) as session:
                        # 标准化URL路径
                        from urllib.parse import urljoin
                        normalized_url = urljoin(url.rstrip('/') + '/', tool_name.lstrip('/'))
                        
                        async with session.post(
                            normalized_url,
                            headers=headers,
                            json=payload
                        ) as response:
                            # 检查响应状态码
                            if response.status == 401:
                                raise MCPAuthenticationError(f"认证失败: {response.status}", {
                                    "server_name": server_name,
                                    "status_code": response.status
                                })
                            elif response.status == 404:
                                raise MCPToolError(f"工具未找到: {tool_name}", {
                                    "server_name": server_name,
                                    "tool_name": tool_name,
                                    "status_code": response.status
                                })
                            elif response.status >= 500:
                                raise MCPServiceError(f"服务器内部错误: {response.status}", "SERVER_ERROR", {
                                    "server_name": server_name,
                                    "status_code": response.status
                                })
                            elif response.status >= 400:
                                raise MCPServiceError(f"客户端错误: {response.status}", "CLIENT_ERROR", {
                                    "server_name": server_name,
                                    "status_code": response.status
                                })
                            
                            if response.status == 200:
                                result = await response.json()
                                return result
                            else:
                                text = await response.text()
                                raise MCPServiceError(f"HTTP错误: {response.status}", "HTTP_ERROR", {
                                    "server_name": server_name,
                                    "status_code": response.status,
                                    "response_text": text[:200]
                                })
                except asyncio.TimeoutError as e:
                    if attempt == retries - 1:  # 最后一次尝试
                        # 记录插件错误统计
                        monitoring_service.record_mcp_plugin_error("unknown", server_name, tool_name, "TIMEOUT")
                        raise MCPTimeoutError(f"异步调用MCP工具超时", {
                            "server_name": server_name,
                            "tool_name": tool_name,
                            "timeout": timeout,
                            "attempt": attempt + 1
                        }) from e
                    # 使用新的重试逻辑处理
                    import random
                    delay = (2 ** attempt) + (random.uniform(0, 1))
                    logger.warning(f"异步MCP工具调用超时 (尝试 {attempt + 1}/{retries})，等待 {delay:.2f} 秒后重试")
                    await asyncio.sleep(delay)
                except aiohttp.ClientError as e:
                    if attempt == retries - 1:  # 最后一次尝试
                        # 记录插件错误统计
                        monitoring_service.record_mcp_plugin_error("unknown", server_name, tool_name, "CONNECTION_ERROR")
                        raise MCPConnectionError(f"异步连接MCP服务器失败: {str(e)}", {
                            "server_name": server_name,
                            "tool_name": tool_name,
                            "attempt": attempt + 1
                        }) from e
                    # 使用新的重试逻辑处理
                    import random
                    delay = (2 ** attempt) + (random.uniform(0, 1))
                    logger.warning(f"异步连接MCP服务器失败 (尝试 {attempt + 1}/{retries}): {e}，等待 {delay:.2f} 秒后重试")
                    await asyncio.sleep(delay)
                except MCPServiceError:
                    # 重新抛出已知的MCP异常
                    raise
                except Exception as e:
                    if attempt == retries - 1:  # 最后一次尝试
                        # 记录插件错误统计
                        monitoring_service.record_mcp_plugin_error("unknown", server_name, tool_name, "ASYNC_REQUEST_ERROR")
                        raise MCPServiceError(f"异步调用MCP工具失败: {str(e)}", "ASYNC_REQUEST_ERROR", {
                            "server_name": server_name,
                            "tool_name": tool_name,
                            "attempt": attempt + 1
                        }) from e
                    # 使用新的重试逻辑处理
                    import random
                    delay = (2 ** attempt) + (random.uniform(0, 1))
                    logger.warning(f"异步MCP工具调用失败 (尝试 {attempt + 1}/{retries}): {e}，等待 {delay:.2f} 秒后重试")
                    await asyncio.sleep(delay)
            
            # 默认返回值
            return {"status": "unknown", "message": "未知错误"}
        except MCPServiceError:
            # 重新抛出已知的MCP异常
            status = "error"
            raise
        except Exception as e:
            status = "error"
            error_details = {
                "server_name": server_name,
                "tool_name": tool_name,
                "error_type": type(e).__name__,
                "error_message": str(e)
            }
            self._log_error_with_context(e, error_context)
            # 记录插件错误统计
            monitoring_service.record_mcp_plugin_error("unknown", server_name, tool_name, "UNEXPECTED_ASYNC_ERROR")
            raise MCPServiceError(f"异步MCP工具调用失败: {str(e)}", "UNEXPECTED_ASYNC_ERROR", error_details) from e
        finally:
            # 记录监控指标
            try:
                duration = asyncio.get_event_loop().time() - start_time
                monitoring_service.record_mcp_server_request(server_name, tool_name, status, duration)
                # 记录调用链追踪
                monitoring_service.record_mcp_call_trace(server_name, tool_name, status, caller, workflow)
                monitoring_service.record_mcp_call_latency(server_name, tool_name, duration, caller, workflow)
                # 记录插件响应时间
                monitoring_service.record_mcp_plugin_response_time("unknown", server_name, tool_name, duration)
            except Exception as e:
                logger.warning(f"记录MCP监控指标失败: {e}")
    
    def get_all_servers_status(self) -> List[Dict[str, Any]]:
        """
        获取所有MCP服务器状态
        
        Returns:
            服务器状态列表
        """
        statuses = []
        for server_name in settings.MCP_SERVERS:
            try:
                status = self.get_server_status(server_name)
                statuses.append(status)
            except Exception as e:
                error_details = {
                    "server_name": server_name,
                    "error_type": type(e).__name__,
                    "error_message": str(e)
                }
                self._log_error_with_context(e, {
                    "operation": "get_all_servers_status",
                    "server_name": server_name
                })
                statuses.append({
                    "server_name": server_name,
                    "enabled": False,
                    "config": {},
                    "tools": [],
                    "error": f"获取状态失败: {str(e)}",
                    "error_details": error_details
                })
        return statuses
    
    def get_server_status(self, server_name: str) -> Dict[str, Any]:
        """
        获取特定MCP服务器状态
        
        Args:
            server_name: 服务器名称
            
        Returns:
            服务器状态信息
        """
        # 检查缓存
        cache_key = f"status_{server_name}"
        if cache_key in self._status_cache:
            cached_time, cached_status = self._status_cache[cache_key]
            if time.time() - cached_time < self._status_cache_ttl:
                return cached_status
            else:
                # 缓存过期，删除缓存项
                del self._status_cache[cache_key]
        
        try:
            if not self.is_server_available(server_name):
                return {
                    "server_name": server_name,
                    "enabled": False,
                    "config": {},
                    "tools": [],
                    "error": "服务器不可用或未启用"
                }
            
            config = self.get_server_config(server_name)
            tools = []
            error = None
            
            try:
                # 尝试获取工具列表
                tools_response = self.call_tool_sync(server_name, "list_tools", {})
                tools = tools_response.get("tools", [])
            except MCPServiceError as e:
                error = f"获取工具列表失败: {e.message}"
                logger.warning(f"获取服务器 {server_name} 工具列表失败: {e.message}")
            except Exception as e:
                error = f"获取工具列表异常: {str(e)}"
                self._log_error_with_context(e, {
                    "operation": "get_server_status",
                    "server_name": server_name,
                    "sub_operation": "list_tools"
                })
            
            result = {
                "server_name": server_name,
                "enabled": True,
                "config": config,
                "tools": tools,
                "error": error
            }
            
            # 缓存结果
            self._status_cache[cache_key] = (time.time(), result)
            return result
        except Exception as e:
            error_details = {
                "server_name": server_name,
                "error_type": type(e).__name__,
                "error_message": str(e)
            }
            self._log_error_with_context(e, {
                "operation": "get_server_status",
                "server_name": server_name
            })
            return {
                "server_name": server_name,
                "enabled": False,
                "config": {},
                "tools": [],
                "error": f"获取状态失败: {str(e)}",
                "error_details": error_details
            }
    
    async def health_check(self, server_name: str) -> Dict[str, Any]:
        """
        检查MCP服务器健康状态
        
        Args:
            server_name: 服务器名称
            
        Returns:
            健康检查结果
        """
        try:
            if not self.is_server_available(server_name):
                return {
                    "server_name": server_name,
                    "status": "unavailable",
                    "message": "服务器不可用或未启用",
                    "timestamp": time.time()
                }
            
            # 执行多项健康检查
            checks = {
                "connectivity": False,
                "authentication": False,
                "tool_discovery": False,
                "response_time": None
            }
            
            start_time = time.time()
            
            # 1. 基本连通性检查
            try:
                config = self.get_server_config(server_name)
                url = config.get('url', '')
                if url:
                    response = self.session.get(url, timeout=5)
                    checks["connectivity"] = response.status_code < 400
            except Exception:
                checks["connectivity"] = False
            
            # 2. 认证检查
            if checks["connectivity"]:
                try:
                    # 尝试调用一个简单的工具来验证认证
                    await self.call_tool_async(server_name, "health_check", {}, "health_check", "system")
                    checks["authentication"] = True
                except MCPAuthenticationError:
                    checks["authentication"] = False
                except Exception:
                    # 其他错误不代表认证失败
                    checks["authentication"] = True
            
            # 3. 工具发现检查
            if checks["connectivity"]:
                try:
                    tools_response = await self.call_tool_async(server_name, "list_tools", {}, "health_check", "system")
                    checks["tool_discovery"] = isinstance(tools_response.get("tools"), list)
                except Exception:
                    checks["tool_discovery"] = False
            
            checks["response_time"] = time.time() - start_time
            
            # 综合评估健康状态
            healthy_checks = sum([1 for k, v in checks.items() if v and k != "response_time"])
            total_checks = len([k for k in checks.keys() if k != "response_time"])
            
            if healthy_checks == total_checks:
                status = "healthy"
            elif healthy_checks >= total_checks // 2:
                status = "degraded"
            else:
                status = "unhealthy"
            
            return {
                "server_name": server_name,
                "status": status,
                "message": f"服务器健康状态: {status}",
                "checks": checks,
                "timestamp": time.time()
            }
        except Exception as e:
            self._log_error_with_context(e, {
                "operation": "health_check",
                "server_name": server_name
            })
            return {
                "server_name": server_name,
                "status": "error",
                "message": f"健康检查处理失败: {str(e)}"
            }
    
    async def register_and_verify_plugin(self, plugin_config: Dict[str, Any]) -> Dict[str, Any]:
        """注册并验证插件"""
        try:
            # 加载插件
            plugin = await self.load_plugin(plugin_config)
            
            # 检查兼容性
            compatibility_report = self.compatibility_checker.check_plugin_compatibility(
                plugin, plugin_config.get('name', 'unknown')
            )
            
            # 如果不兼容，可以选择是否继续注册
            if not compatibility_report['compatible']:
                logger.warning(f"插件 {plugin_config.get('name', 'unknown')} 不兼容: {compatibility_report['issues']}")
                # 根据策略决定是否继续
            
            # 注册插件
            registration_result = await self.register_plugin(plugin_config)
            
            return {
                'registration_success': registration_result,
                'compatibility_report': compatibility_report
            }
            
        except Exception as e:
            logger.error(f"注册并验证插件时出错: {e}")
            raise MCPServiceError(f"插件注册失败: {str(e)}")

    async def load_plugin(self, plugin_config: Dict[str, Any]) -> Any:
        """
        加载插件
        
        Args:
            plugin_config: 插件配置
            
        Returns:
            加载的插件对象
        """
        plugin_name = plugin_config.get('name', 'unknown')
        plugin_version = plugin_config.get('version', '1.0.0')
        logger.info(f"开始加载插件: {plugin_name} v{plugin_version}")
        
        try:
            # 检查插件依赖
            dependencies = plugin_config.get('dependencies', [])
            if dependencies:
                for dep in dependencies:
                    if not self._check_dependency(dep):
                        raise MCPServiceError(f"插件依赖未满足: {dep}")
            
            # 检查插件版本兼容性
            if not self._check_version_compatibility(plugin_version):
                logger.warning(f"插件版本可能不兼容: {plugin_name} v{plugin_version}")
            
            # 这里应该根据plugin_config中的信息加载插件
            # 示例实现可能包括:
            # 1. 从指定路径导入插件模块
            # 2. 实例化插件类
            # 3. 执行插件初始化逻辑
            
            # 当前为示例实现，实际应根据配置加载具体插件
            plugin_type = plugin_config.get('type', 'default')
            
            if plugin_type == 'default':
                # 创建一个简单的插件对象占位符
                plugin = type('MCPPlugin', (), {
                    'name': plugin_name,
                    'config': plugin_config,
                    'is_loaded': True,
                    'version': plugin_version
                })()
                logger.info(f"插件 {plugin_name} 加载成功")
                return plugin
            else:
                # 其他类型的插件加载逻辑
                logger.warning(f"未知的插件类型: {plugin_type}，使用默认加载方式")
                plugin = type('MCPPlugin', (), {
                    'name': plugin_name,
                    'config': plugin_config,
                    'is_loaded': True,
                    'version': plugin_version
                })()
                return plugin
                
        except Exception as e:
            logger.error(f"加载插件 {plugin_name} 失败: {e}")
            raise MCPServiceError(f"插件加载失败: {str(e)}")
    
    def _check_dependency(self, dependency: str) -> bool:
        """
        检查插件依赖
        
        Args:
            dependency: 依赖描述
            
        Returns:
            依赖是否满足
        """
        # 简单实现，实际应检查具体依赖
        logger.info(f"检查依赖: {dependency}")
        return True
    
    def _check_version_compatibility(self, version: str) -> bool:
        """
        检查版本兼容性
        
        Args:
            version: 插件版本
            
        Returns:
            版本是否兼容
        """
        # 简单实现，实际应检查版本兼容性
        logger.info(f"检查版本兼容性: {version}")
        return True
    
    async def register_plugin(self, plugin_config: Dict[str, Any]) -> bool:
        """
        注册插件
        
        Args:
            plugin_config: 插件配置
            
        Returns:
            注册是否成功
        """
        plugin_name = plugin_config.get('name', 'unknown')
        logger.info(f"开始注册插件: {plugin_name}")
        
        try:
            # 这里应该实现插件注册逻辑
            # 示例实现可能包括:
            # 1. 验证插件配置
            # 2. 将插件注册到系统中
            # 3. 更新插件状态
            
            # 模拟注册过程
            is_enabled = plugin_config.get('enabled', True)
            
            if is_enabled:
                # 模拟注册延迟
                await asyncio.sleep(0.1)
                logger.info(f"插件 {plugin_name} 注册成功")
                return True
            else:
                logger.info(f"插件 {plugin_name} 未启用，跳过注册")
                return False
                
        except Exception as e:
            logger.error(f"注册插件 {plugin_name} 失败: {e}")
            raise MCPServiceError(f"插件注册失败: {str(e)}")

    def add_feedback(self, server_name: str, user_id: str, feedback: str, feedback_type: str = "general", 
                    metadata: Optional[Dict[str, Any]] = None, priority: str = "medium") -> Dict[str, Any]:
        """
        添加用户对MCP服务的反馈
        
        Args:
            server_name: 服务器名称
            user_id: 用户ID
            feedback: 反馈内容
            feedback_type: 反馈类型 (general, performance, error, suggestion, security)
            metadata: 反馈元数据
            priority: 反馈优先级 (low, medium, high, critical)
            
        Returns:
            添加反馈的结果
        """
        try:
            # 验证反馈类型
            valid_feedback_types = ["general", "performance", "error", "suggestion", "security"]
            if feedback_type not in valid_feedback_types:
                return {
                    "success": False,
                    "error": f"无效的反馈类型: {feedback_type}，有效类型: {valid_feedback_types}"
                }
            
            # 验证优先级
            valid_priorities = ["low", "medium", "high", "critical"]
            if priority not in valid_priorities:
                return {
                    "success": False,
                    "error": f"无效的优先级: {priority}，有效优先级: {valid_priorities}"
                }
            
            # 创建反馈记录
            feedback_entry = {
                "server_name": server_name,
                "user_id": user_id,
                "feedback": feedback,
                "feedback_type": feedback_type,
                "priority": priority,
                "timestamp": time.time(),
                "processed": False,
                "metadata": metadata or {}
            }
            
            # 初始化服务器反馈历史
            if server_name not in self._feedback_history:
                self._feedback_history[server_name] = []
            
            # 添加反馈到历史记录
            self._feedback_history[server_name].append(feedback_entry)
            
            # 记录到监控系统
            monitoring_service.record_mcp_feedback(server_name, feedback_type)
            
            logger.info(f"收到用户 {user_id} 对服务器 {server_name} 的反馈: {feedback} (类型: {feedback_type}, 优先级: {priority})")
            
            return {
                "success": True,
                "message": "反馈已成功记录",
                "feedback_id": len(self._feedback_history[server_name]) - 1
            }
        except Exception as e:
            error_details = {
                "server_name": server_name,
                "user_id": user_id,
                "feedback": feedback,
                "error_type": type(e).__name__,
                "error_message": str(e)
            }
            self._log_error_with_context(e, {
                "operation": "add_feedback",
                "server_name": server_name,
                "user_id": user_id
            })
            return {
                "success": False,
                "error": f"记录反馈失败: {str(e)}",
                "error_details": error_details
            }

    def get_feedback_history(self, server_name: str, limit: int = 50) -> List[Dict[str, Any]]:
        """
        获取特定服务器的反馈历史
        
        Args:
            server_name: 服务器名称
            limit: 返回的最大反馈数量
            
        Returns:
            反馈历史列表
        """
        if server_name in self._feedback_history:
            # 返回最近的反馈，按时间倒序排列
            feedback_list = self._feedback_history[server_name]
            return sorted(feedback_list, key=lambda x: x['timestamp'], reverse=True)[:limit]
        return []

    def process_feedback(self, server_name: str, strategy: str = "auto", 
                        custom_thresholds: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """
        处理服务器反馈并根据反馈调整服务配置
        
        Args:
            server_name: 服务器名称
            strategy: 处理策略 (auto, ignore, restart, reconfigure)
            custom_thresholds: 自定义阈值配置
            
        Returns:
            处理结果
        """
        try:
            if server_name not in self._feedback_history:
                return {
                    "success": False,
                    "message": f"服务器 {server_name} 没有反馈历史"
                }
            
            # 获取未处理的反馈
            feedback_list = [f for f in self._feedback_history[server_name] if not f.get('processed', False)]
            
            if not feedback_list:
                return {
                    "success": True,
                    "message": "没有未处理的反馈"
                }
            
            # 分析反馈类型和严重程度
            feedback_analysis = {
                "performance": 0,
                "error": 0,
                "suggestion": 0,
                "general": 0,
                "security": 0
            }
            
            # 计算反馈严重程度（基于类型权重和优先级）
            severity_weights = {
                "performance": 2,
                "error": 3,
                "suggestion": 1,
                "general": 1,
                "security": 4  # 安全反馈权重最高
            }
            
            priority_multipliers = {
                "low": 1,
                "medium": 2,
                "high": 3,
                "critical": 5  # 关键优先级乘数最高
            }
            
            total_severity = 0
            for feedback in feedback_list:
                feedback_type = feedback.get("feedback_type", "general")
                priority = feedback.get("priority", "medium")
                
                type_weight = severity_weights.get(feedback_type, 1)
                priority_multiplier = priority_multipliers.get(priority, 2)
                
                feedback_severity = type_weight * priority_multiplier
                total_severity += feedback_severity
                
                # 统计各类型反馈数量
                if feedback_type in feedback_analysis:
                    feedback_analysis[feedback_type] += 1
            
            # 根据策略处理反馈
            actions_taken = []
            
            # 获取阈值配置
            thresholds = {
                "error_threshold": 3,
                "severity_threshold": 8,
                "performance_threshold": 2,
                "suggestion_threshold": 3,
                "security_threshold": 1  # 安全问题只要有就处理
            }
            
            if custom_thresholds:
                thresholds.update(custom_thresholds)
            
            if strategy == "auto":
                # 更智能的自动处理策略
                if feedback_analysis["security"] >= thresholds["security_threshold"]:
                    # 安全问题优先处理
                    self._handle_security_issue(server_name, feedback_list)
                    actions_taken.append("security_handled")
                    monitoring_service.record_mcp_feedback_processed(server_name, "security_handled")
                elif feedback_analysis["error"] >= thresholds["error_threshold"] or total_severity >= thresholds["severity_threshold"]:
                    # 严重错误或高严重性反馈，重启服务
                    self._restart_server(server_name)
                    actions_taken.append("server_restart")
                    monitoring_service.record_mcp_feedback_processed(server_name, "server_restart")
                elif feedback_analysis["performance"] >= thresholds["performance_threshold"]:
                    # 性能问题，调整配置
                    self._adjust_server_config(server_name, "performance")
                    actions_taken.append("performance_tuning")
                    monitoring_service.record_mcp_feedback_processed(server_name, "performance_tuning")
                elif feedback_analysis["suggestion"] >= thresholds["suggestion_threshold"]:
                    # 大量建议，记录需求
                    self._log_suggestions(server_name, feedback_list)
                    actions_taken.append("suggestions_recorded")
                    monitoring_service.record_mcp_feedback_processed(server_name, "suggestions_recorded")
                else:
                    # 一般反馈，记录但不采取行动
                    actions_taken.append("feedback_recorded")
                    monitoring_service.record_mcp_feedback_processed(server_name, "feedback_recorded")
            elif strategy == "restart":
                self._restart_server(server_name)
                actions_taken.append("server_restart")
                monitoring_service.record_mcp_feedback_processed(server_name, "server_restart")
            elif strategy == "reconfigure":
                self._adjust_server_config(server_name, "general")
                actions_taken.append("config_adjustment")
                monitoring_service.record_mcp_feedback_processed(server_name, "config_adjustment")
            
            # 标记反馈为已处理
            for feedback in feedback_list:
                feedback["processed"] = True
                feedback["processed_at"] = time.time()
                feedback["processing_strategy"] = strategy
            
            # 缓存处理结果
            self._feedback_cache[server_name] = {
                "last_processed": time.time(),
                "actions_taken": actions_taken,
                "feedback_analysis": feedback_analysis,
                "total_severity": total_severity
            }
            
            logger.info(f"处理了服务器 {server_name} 的 {len(feedback_list)} 条反馈，总严重性评分: {total_severity}")
            
            return {
                "success": True,
                "message": f"成功处理 {len(feedback_list)} 条反馈",
                "feedback_analysis": feedback_analysis,
                "actions_taken": actions_taken,
                "total_severity": total_severity,
                "thresholds_used": thresholds
            }
        except Exception as e:
            self._log_error_with_context(e, {
                "operation": "process_feedback",
                "server_name": server_name
            })
            return {
                "success": False,
                "error": f"处理反馈失败: {str(e)}"
            }

    def _restart_server(self, server_name: str):
        """
        重启MCP服务器
        
        Args:
            server_name: 服务器名称
        """
        logger.info(f"重启服务器 {server_name}")
        # 清除服务器缓存
        cache_keys_to_remove = []
        for cache_key in self._status_cache:
            if cache_key.startswith(f"status_{server_name}"):
                cache_keys_to_remove.append(cache_key)
        
        for cache_key in cache_keys_to_remove:
            del self._status_cache[cache_key]
        
        # 重新初始化服务器会话
        config = self.get_server_config(server_name)
        if 'url' in config:
            # 重新创建会话适配器
            self.session.mount(config['url'], HTTPAdapter(max_retries=3))
        
        # 这里应该实现实际的服务器重启逻辑
        # 例如：关闭连接、重新初始化等

    def _adjust_server_config(self, server_name: str, adjustment_type: str):
        """
        调整服务器配置
        
        Args:
            server_name: 服务器名称
            adjustment_type: 调整类型 (performance, general)
        """
        logger.info(f"调整服务器 {server_name} 配置，类型: {adjustment_type}")
        # 获取当前配置
        config = self.get_server_config(server_name)
        
        # 根据调整类型进行具体调整
        if adjustment_type == "performance":
            # 性能调优
            current_timeout = config.get("timeout", 30)
            new_timeout = min(current_timeout * 2, 300)  # 最多增加到300秒
            
            current_retries = config.get("retries", 3)
            new_retries = min(current_retries + 1, 5)  # 最多重试5次
            
            logger.info(f"性能调优: 超时时间从 {current_timeout} 调整为 {new_timeout}，重试次数从 {current_retries} 调整为 {new_retries}")
            
            # 更新配置
            config["timeout"] = new_timeout
            config["retries"] = new_retries
            
            # 更新系统配置
            settings.update_mcp_server_config(server_name, config)
        else:
            # 通用调整
            logger.info("执行通用配置调整")
            # 可以添加更多通用调整逻辑

    def _handle_security_issue(self, server_name: str, feedback_list: List[Dict[str, Any]]):
        """
        处理安全问题
        
        Args:
            server_name: 服务器名称
            feedback_list: 反馈列表
        """
        logger.warning(f"处理服务器 {server_name} 的安全问题")
        
        # 获取安全相关反馈
        security_feedback = [f for f in feedback_list if f.get("feedback_type") == "security"]
        
        # 记录安全问题
        for feedback in security_feedback:
            logger.warning(f"安全反馈 [{feedback.get('priority', 'medium')}]: {feedback.get('feedback', '无内容')}")
        
        # 实施安全措施（示例）
        # 1. 暂时隔离服务器
        # 2. 增加日志记录级别
        # 3. 通知安全团队
        
        logger.warning(f"已记录 {len(security_feedback)} 条安全问题，建议立即审查服务器 {server_name} 的安全配置")

    def _log_suggestions(self, server_name: str, feedback_list: List[Dict[str, Any]]):
        """
        记录用户建议
        
        Args:
            server_name: 服务器名称
            feedback_list: 反馈列表
        """
        suggestions = [f["feedback"] for f in feedback_list if f.get("feedback_type") == "suggestion"]
        logger.info(f"服务器 {server_name} 收到 {len(suggestions)} 条建议: {suggestions}")
        
        # 可以将建议写入文件或数据库以供后续分析
        # 这里仅记录日志

    def get_feedback_summary(self, server_name: str) -> Dict[str, Any]:
        """
        获取服务器反馈摘要
        
        Args:
            server_name: 服务器名称
            
        Returns:
            反馈摘要信息
        """
        if server_name not in self._feedback_history:
            return {
                "server_name": server_name,
                "total_feedback": 0,
                "feedback_by_type": {},
                "last_feedback": None
            }
        
        feedback_list = self._feedback_history[server_name]
        
        # 统计各类型反馈数量
        feedback_by_type = {}
        for feedback in feedback_list:
            feedback_type = feedback.get("feedback_type", "general")
            feedback_by_type[feedback_type] = feedback_by_type.get(feedback_type, 0) + 1
        
        # 获取最新反馈
        last_feedback = None
        if feedback_list:
            last_feedback = sorted(feedback_list, key=lambda x: x['timestamp'], reverse=True)[0]
        
        # 计算平均优先级
        priority_scores = {"low": 1, "medium": 2, "high": 3, "critical": 5}
        total_priority_score = 0
        feedback_count = len(feedback_list)
        
        for feedback in feedback_list:
            priority = feedback.get("priority", "medium")
            total_priority_score += priority_scores.get(priority, 2)
        
        avg_priority = total_priority_score / feedback_count if feedback_count > 0 else 0
        
        return {
            "server_name": server_name,
            "total_feedback": feedback_count,
            "feedback_by_type": feedback_by_type,
            "last_feedback": last_feedback,
            "average_priority": round(avg_priority, 2),
            "high_priority_count": sum(1 for f in feedback_list if f.get("priority", "") in ["high", "critical"])
        }

# 创建MCPServiceManager实例
mcp_service_manager = MCPServiceManager()

